package com.kaiming.processor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.LocalDateTime;

/**
 * ClassName: TimeLogBeanPostProcessor
 * Package: com.kaiming.processor
 * Description:
 *
 * @Auther gongkaiming
 * @Create 2025/10/25 11:52
 * @Version 1.0
 */
public class TimeLogBeanPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        
        // 使用动态代理对目标bean进行增强，返回Proxy对象，进而存储到SingletonObjects中
        Object beanProxy = Proxy.newProxyInstance(
                bean.getClass().getClassLoader(),
                bean.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    // 输出开始时间
                    System.out.println("方法: " + method.getName() + "-开始时间: " + LocalDateTime.now());
                    // 执行目标方法
                    Object results = method.invoke(bean, args);
                    // 输出结束时间
                    System.out.println("方法: " + method.getName() + "-结束时间: " + LocalDateTime.now());

                    return results;
                }
        );
        return beanProxy;
        
    }
}
